package cn.zuo.service;

import cn.zuo.pojo.Message;
import cn.zuo.utils.*;
import cn.zuo.view.ChatJFrame;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author 白白旧维
 * @Date 2021/7/7 11:13
 */
public class Receive extends Thread {//用来接收信息的线程类

    private Socket s;
//    private String seed;
    private BigInteger login_d;//登录用的私钥d
    private BigInteger login_n;//登录用的私钥n
    private String name;
    private Jedis jedis = new Jedis("127.0.0.1",6379);
    private Lock lock = new ReentrantLock();

    public Socket getS() {
        return s;
    }

    public Receive(Socket s,String name,BigInteger login_d,BigInteger login_n) {
        this.s = s;
        this.name = name;
        this.login_d = login_d;
        this.login_n = login_n;
    }

    @Override
    public void run() {
        while(true){
            try {
                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());

                Message msg = (Message) ois.readObject();

                if("redis".equals(msg.getStatus())){
                    RedisCtrl.setIsOpen(Boolean.parseBoolean(msg.getMsg()));
                    System.out.println("redis状态改变为"+RedisCtrl.isIsOpen());
                    continue;
                }

                if("chat".equals(msg.getStatus())){//给指定聊天池中的聊天添加信息
//                    System.out.println("1、接收到："+msg);
                    // msg需要解密
                    String key = msg.getReceiver() + "_" + msg.getSender();

                    lock.lock();
                    ChatJFrame chat = ChatPool.getChat(key);
                    if(chat==null){//获取信息，添加后，再写入缓存
                        if(RedisCtrl.isIsOpen()){
                            String info_json = jedis.get(key);
                            List<String> infos = JSONArray.parseArray(info_json, String.class);
                            if(infos==null){
                                infos = new ArrayList<>();
                            }
                            infos.add(msg.getMsg());

//                            System.out.println(info_json);
                            String infos_json = JSON.toJSONString(infos);
                            jedis.set(key,infos_json);
                            jedis.expire(key,30);

                            System.out.println("写入缓存完毕");
                        }

                    }else{
                        chat.addMsg(msg);
                    }
                    lock.unlock();

                    continue;
                }
                if("file".equals(msg.getStatus())){
                    String key = msg.getReceiver() + "_" + msg.getSender();

                    ChatJFrame chat = ChatPool.getChat(key);
                    if(chat==null){//获取信息，添加后，再写入缓存

                    }else{
                        chat.addMsg(msg);
                    }

                    continue;
                }

                if("key".equals(msg.getStatus())){//新：旧：保存别人的公钥
                    String other = msg.getSender();
                    BigInteger e = new BigInteger(msg.getMsg().split("_")[0]);
                    BigInteger n = new BigInteger(msg.getMsg().split("_")[1]);
                    PublicKeyPool.setKey_e(other,e);
                    PublicKeyPool.setKey_n(other,n);
                    System.out.println(name+"得到别人的公钥："+msg);
                    continue;

                }

                if("aes".equals(msg.getStatus())){//Aes密钥seed保存
                    //先把aes密钥解密
                    String en_seed_json = msg.getMsg();
                    List<BigInteger> en_seed = JSONArray.parseArray(en_seed_json, BigInteger.class);
                    String seed = RSA.decryption_mul(login_d, login_n, en_seed);
//                    this.seed = seed;
                    System.out.println(name+"在Receive接收到seed，并保存到AESKey库中");
                    AESRandomKey.setSeed(seed);

                }

            } catch (Exception e) {
//                e.printStackTrace();
            }

        }
    }
}
